package cn.highedu.spring03.converter;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
@Component
public class ExcelMessageConverter implements HttpMessageConverter {
    private Class excelObjectClass = XSSFWorkbook.class; // 获取XSSFWorkbook的运行时类对象
    private MediaType mediaType = new MediaType("application", "xlsx");
    @Override
    public boolean canRead(Class clazz, MediaType mediaType) {
        return false;
    }

    @Override
    public boolean canWrite(Class clazz, MediaType mediaType) {
        if (clazz.equals(excelObjectClass)) {
            return true; // 文件可写
        }
        return false;
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        List<MediaType> list = new ArrayList<>();
        list.add(mediaType);
        return list;
    }

    @Override
    public Object read(Class clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        String contentT = "application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet";
        if (!(o instanceof XSSFWorkbook)) {
            return;
        }
        XSSFWorkbook workbook = (XSSFWorkbook) o;
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        workbook.write(buf);
        workbook.close();
        buf.close();

        byte[] bytes = buf.toByteArray();
        ServletServerHttpResponse response = (ServletServerHttpResponse) outputMessage;
        response.getServletResponse().addHeader("Content-Length", bytes.length + "");
        response.getServletResponse().addHeader("Content-Type", contentT);
        response.getBody().write(bytes);
        // 创建文件名
        String fileName = "file.xlsx";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.getServletResponse().addHeader("Content-Disposition", "attachment;filename=" + fileName);
    }
}
